import socket
from mcrcon import MCRcon
import writer

# 配置RCON连接
RCON_HOST = '127.0.0.1'  # 服务器IP地址
RCON_PORT = 1337       # RCON端口
RCON_PASSWORD = 'fish_city_nb'  # RCON密码

def send_rcon_command(command):
    """
    向Minecraft服务器发送RCON命令。

    参数:
        command (str): 要发送的RCON命令。
    """
    try:
        with MCRcon(RCON_HOST, RCON_PASSWORD, port=RCON_PORT) as mcr:
            # 发送RCON命令
            resp = mcr.command(command)
            print(f"服务器响应: {resp}")
    except Exception as e:
        print(f"发送RCON命令时出错: {e}")

def server_program():
    # 创建socket对象
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定到所有网络接口的12345端口
    server_socket.bind(('0.0.0.0', 12345))
    # 开始监听
    server_socket.listen(5)
    print("服务器已经在 12345 端口上监听啦，快去试试！")

    while True:
        # 接受客户端连接
        conn, addr = server_socket.accept()
        print(f"哇哦！{addr} 连上了服务器！")
        
        # 接收数据
        data = conn.recv(4096)
        if data:
            message = data.decode()
            print(f"好耶！从 {addr} 收到了一条消息: {message}")
            if "[sf]" in message:
                write_configure("slimefun",message.strip("[sf]"))
                send_rcon_command("velocity reload")
                print("已经替换配置文件完成了喵")
            if "[sv]" in message:
                write_configure("server",message.strip("[sv]"))
                send_rcon_command("velocity reload")
                print("已经替换配置文件完成了喵")

        
        # 关闭连接
        conn.close()
        print(f"啊哦！{addr} 关闭了链接....")

if __name__ == '__main__':
    server_program()
